<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" preIcon="ion:add-outline" @click="handleAdd">新建</a-button>
        <a-button
          type="dashed"
          preIcon="ion:ios-printer-outline"
          style="margin-left: 10px"
          @click="handleReport"
        >
          报表打印
        </a-button>
        <a-button type="dashed" preIcon="ion:download-outline" style="margin-left: 10px">
          project导入
        </a-button>
      </template>
      <!-- 项目状态 -->
      <template #status="{ text: status }">
        <span>
          <Tag
            :color="
              status == 0
                ? 'default'
                : status == 1
                ? 'processing'
                : status == 2
                ? 'success'
                : status == 3
                ? 'error'
                : 'warning'
            "
            >{{ proxy.$filters.filterProjStatus(status) }}</Tag
          >
        </span>
      </template>
      <!-- 计划开始时间 -->
      <template #prestarttime="{ text: prestarttime }">
        <span>
          {{ proxy.$filters.filterTime(prestarttime) }}
        </span>
      </template>
      <!-- 计划结束时间 -->
      <template #preEndTime="{ text: preEndTime }">
        <span>
          {{ proxy.$filters.filterTime(preEndTime) }}
        </span>
      </template>
      <!-- 创建时间 -->
      <template #creationTime="{ text: creationTime }">
        <span>
          {{ proxy.$filters.filterTime(creationTime) }}
        </span>
      </template>
      <!-- 完成进度 -->
      <template #overdue="{ text: overdue }">
        <span>
          {{
            overdue > 0
              ? '提前' + overdue + '天'
              : overdue == 0
              ? '正常'
              : '延期' + Math.abs(overdue) + '天'
          }}
        </span>
      </template>
      <!-- 完成比例 -->
      <template #completeRatio="{ text: completeRatio }">
        <span>
          <Progress :percent="completeRatio" size="small" />
        </span>
      </template>
      <!-- 成本差距 -->
      <template #costDifference="{ text: costDifference }">
        <span>
          {{ Math.abs(costDifference) }}
          <Icon icon="lucide:move-up" color="red" v-if="costDifference > 0" />
          <Icon icon="lucide:move-down" color="green" v-else-if="costDifference < 0" />
        </span>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '启动',
              icon: 'ion:caret-forward-circle-outline',
              onClick: handleOpen.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '详情',
              icon: 'ion:reorder-four-outline',
              onClick: handleDetail.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '删除',
              icon: 'ic:outline-delete-outline',
              onClick: handleDelete.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
          ]"
          :dropDownActions="[
            {
              label: '设为模板',
              icon: 'ion:settings-outline',
              onClick: handleSetTemplate.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '手动归档',
              icon: 'ion:refresh-circle-outline',
              onClick: handleManualArchive.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '导出项目',
              icon: 'ion:share-outline',
              onClick: handleExport.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '终止项目',
              icon: 'ion:md-close-circle-outline',
              onClick: handleTerminate.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '分享项目',
              icon: 'ion:share-social-outline',
              onClick: handleShare.bind(null, record),
              // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            },
          ]"
        />
      </template>
    </BasicTable>

    <!-- 新建项目弹窗 -->
    <addProjectModal @register="registerModal" @success="reload()" />
    <!-- 选择报表模板弹窗 -->
    <printReport @register="registerReportModal" />
  </div>
</template>
<script lang="ts" setup>
  import { Tag, Progress } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { getBasicColumns, getFormConfig } from './tableData';
  import { projectListApi, deleteProjectApi } from '/@/api/demo/project';
  import { useUserStore } from '/@/store/modules/user';
  import { getCurrentInstance } from 'vue';
  import addProjectModal from './addProject.vue';
  import { useModal } from '/@/components/Modal';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import printReport from './printReport.vue';

  const router = useRouter();
  const { proxy }: any = getCurrentInstance();
  const useCommonStore = useUserStore();
  const { createConfirm, createMessage } = useMessage();
  const [registerTable, { reload }] = useTable({
    api: projectListApi,
    beforeFetch: (params) => {
      params.userid = useCommonStore.userInfo?.userId;
    },
    fetchSetting: {
      // 当前页传递给后台的字段名称
      pageField: 'CurrentPage',
      // 后台每页显示的数量字段名称
      sizeField: 'PageSizes',
      // 接口返回的表单数据字段名称
      listField: 'list1',
      // 接口返回的表格总数字段名称
      totalField: 'count',
    },
    // 分页配置
    pagination: { pageSize: 12, pageSizeOptions: ['12', '24', '36', '48'], defaultPageSize: 12 },
    columns: getBasicColumns(),
    useSearchForm: true,
    formConfig: getFormConfig(), // 表单配置
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    rowKey: 'id',
    bordered: true,
    actionColumn: {
      width: 300,
      fixed: 'right',
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  const [registerModal, { openModal: openModal }] = useModal();
  // 新建项目
  const handleAdd = () => {
    openModal(true);
  };
  // 删除项目
  async function handleDelete(record: Recordable) {
    createConfirm({
      title: `确定删除 ${record.name} ？`,
      iconType: 'warning',
      async onOk() {
        await deleteProjectApi(record.id)
          .then((res) => {
            if (res) {
              createMessage.success('删除成功！');
              reload();
            } else {
              createMessage.error('删除失败！');
            }
          })
          .catch((error) => {
            createMessage.error(error.response.data.error.message);
          });
      },
    });
  }
  const handleOpen = (record: Recordable) => {
    console.log('点击了启动', record);
  };
  const handleDetail = (record: Recordable) => {
    console.log('点击了详情', record);
    router.push({ name: 'projectDetail', params: { id: record.id } });
  };
  const handleSetTemplate = (record: Recordable) => {
    console.log('点击了设置模板', record);
  };
  const handleManualArchive = (record: Recordable) => {
    console.log('点击了手动归档', record);
  };
  const handleExport = (record: Recordable) => {
    console.log('点击了导出项目', record);
  };
  const handleTerminate = (record: Recordable) => {
    console.log('点击了终止项目', record);
  };
  const handleShare = (record: Recordable) => {
    console.log('点击了分享项目', record);
  };
  //报表打印
  const [registerReportModal, { openModal: openReportModal }] = useModal();
  const handleReport = () => {
    openReportModal(true);
  };
</script>
<style lang="less" scoped>
  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }
</style>
